<template>
  <el-dialog
    :visible.sync="visible"
    width="480px"
    :modal-append-to-body="false"
    class="login-dialog"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="login-container">
      <!-- 登录切换标签 -->
      <div class="login-tabs">
        <div
          :class="['tab', activeTab === 'account' ? 'active' : '']"
          @click="switchToAccount"
        >
          账号登录
        </div>
        <div
          :class="['tab', activeTab === 'code' ? 'active' : '']"
          @click="switchToCode"
        >
          验证码登录
        </div>
        <div
          :class="['tab', activeTab === 'register' ? 'active' : '']"
          @click="switchToRegister"
        >
          注册
        </div>
      </div>

      <!-- 账号登录 -->
      <div v-if="activeTab === 'account'">
        <el-input
          v-model="userForm.username"
          placeholder="请输入用户名"
          size="large"
          class="login-input rounded-input"
          :style="{ backgroundColor: '#fff9e6' }"
          clearable
        />
        <el-input
          v-model="userForm.password"
          placeholder="请输入密码"
          size="large"
          class="login-input rounded-input"
          :style="{ backgroundColor: '#fff9e6' }"
          show-password
          clearable
        />
        <div class="form-bottom-row">
          <el-checkbox v-model="autoLogin" class="auto-login">七天内自动登录</el-checkbox>
          <div class="forgot-password">忘记密码?</div>
        </div>
        <el-button type="primary" class="login-btn" @click="login">登录</el-button>
      </div>

      <!-- 验证码登录 -->
      <div v-else-if="activeTab === 'code'">
        <el-input
          v-model="form.email"
          placeholder="请输入邮箱"
          size="large"
          class="login-input rounded-input"
          :style="{ backgroundColor: '#fff9e6' }"
          clearable
          @blur="validateEmail"
        />
        <div v-if="emailError" class="error-hint">{{ emailError }}</div>

        <div class="code-input-wrapper">
          <el-input
            v-model="form.code"
            placeholder="请输入6位验证码"
            size="large"
            class="code-input"
            :style="{ backgroundColor: '#fff9e6' }"
            clearable
          />
          <el-button
            size="large"
            :loading="sendingCode"
            :disabled="!isEmailValid || timer > 0"
            @click="sendCode"
            class="code-btn"
            :class="{ 'countdown-btn': timer > 0 }"
          >
            {{ sendingCode ? '发送中...' : (timer > 0 ? `重新发送 (${timer}s)` : '获取验证码') }}
          </el-button>
        </div>

        <div v-if="codeError" class="error-hint">{{ codeError }}</div>

        <el-button
          type="primary"
          class="login-btn"
          @click="validateEmailLogin"
          :disabled="!isEmailValid || !isCodeValid"
        >
          登录
        </el-button>
      </div>

      <!-- 注册表单 -->
      <div v-else-if="activeTab === 'register'">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入用户名"
          size="large"
          class="login-input rounded-input"
          :style="{ backgroundColor: '#fff9e6' }"
          clearable
        />
        <el-input
          v-model="registerForm.password"
          placeholder="请输入密码"
          size="large"
          class="login-input rounded-input"
          :style="{ backgroundColor: '#fff9e6' }"
          show-password
          clearable
        />
        <el-input
          v-model="registerForm.email"
          placeholder="请输入邮箱"
          size="large"
          class="login-input rounded-input"
          :style="{ backgroundColor: '#fff9e6' }"
          clearable
          @blur="validateRegisterEmail"
        />
        <div v-if="registerEmailError" class="error-hint">{{ registerEmailError }}</div>

        <div class="code-input-wrapper">
          <el-input
            v-model="registerForm.code"
            placeholder="请输入6位验证码"
            size="large"
            class="code-input"
            :style="{ backgroundColor: '#fff9e6' }"
            clearable
          />
          <el-button
            size="large"
            :loading="sendingRegisterCode"
            :disabled="sendingRegisterCode || registerTimer > 0"
            @click="sendRegisterCode"
            class="code-btn"
            :class="{ 'countdown-btn': registerTimer > 0 }"
          >
            {{
              sendingRegisterCode ? '发送中...' : (registerTimer > 0 ? `重新发送 (${registerTimer}s)` : '获取验证码')
            }}
          </el-button>
        </div>

        <div v-if="registerCodeError" class="error-hint">{{ registerCodeError }}</div>

        <el-button
          type="primary"
          class="login-btn"
          @click="register"
          :disabled="!isRegisterEmailValid || !isRegisterCodeValid || !registerForm.username || !registerForm.password"
        >
          注册
        </el-button>
      </div>

      <div class="quick-register" @click="quickRegister">{{ infor }}</div>
      <div class="third-login">
        <el-tooltip content="微信登录"><i class="icon wechat"></i></el-tooltip>
        <el-tooltip content="QQ登录"><i class="icon qq"></i></el-tooltip>
        <el-tooltip content="微博登录"><i class="icon weibo"></i></el-tooltip>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import registerApi from '@/api/register'
import loginApi from '@/api/login'
import indexApi from '@/api/index'

export default {
  name: 'AuthModal',
  data() {
    return {
      infor: '快速注册',
      visible: false,
      activeTab: 'account',
      autoLogin: true,
      showPassword: false,
      userForm: {
        username: '',
        password: '',
      },
      form: {
        email: '',
        code: '',
      },
      registerForm: {
        username: '',
        password: '',
        email: '',
        code: '',
      },
      userInfo: {
        id: '',
        username: '',
        age: '',
        avatar: '',
        sex: '',
        email: ''
      },
      timer: 0,
      registerTimer: 0,
      timerInterval: null,
      registerTimerInterval: null,
      codeError: '',
      emailError: '',
      registerCodeError: '',
      registerEmailError: '',
      sendingCode: false,
      sendingRegisterCode: false,
    };
  },
  computed: {
    isEmailValid() {
      const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return regex.test(this.form.email);
    },
    isCodeValid() {
      const regex = /^\d{6}$/;
      return regex.test(this.form.code);
    },
    isRegisterEmailValid() {
      const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return regex.test(this.registerForm.email);
    },
    isRegisterCodeValid() {
      const regex = /^\d{6}$/;
      return regex.test(this.registerForm.code);
    },
  },
  methods: {
    show(tab = 'account') {
      this.activeTab = tab;
      this.visible = true;
    },
    switchToAccount() {
      this.activeTab = 'account';
      this.infor = '快速注册'
    },
    switchToCode() {
      this.activeTab = 'code';
      this.infor = '快速注册'
    },
    switchToRegister() {
      this.activeTab = 'register';
      this.infor = '已有账号，快速登录'
    },

    handleClose() {
      console.log('关闭.....')
      this.form = {
        username: '',
        password: '',
        email: '',
        code: '',
      };
      this.registerForm = {
        username: '',
        password: '',
        email: '',
        code: '',
      };
      this.timer = 0;
      this.registerTimer = 0;
      if (this.timerInterval) {
        clearInterval(this.timerInterval);
        this.timerInterval = null;
      }
      if (this.registerTimerInterval) {
        clearInterval(this.registerTimerInterval);
        this.registerTimerInterval = null;
      }
      this.showPassword = false;
      this.codeError = '';
      this.emailError = '';
      this.registerCodeError = '';
      this.registerEmailError = '';
      this.sendingCode = false;
      this.sendingRegisterCode = false;
    },

    // 用户账户登录
    async login() {
      if (!this.userForm.username || !this.userForm.password) {
        return this.$message.error('请输入用户名和密码');
      }

      try {
        const res = await loginApi.loginUser(this.userForm)
        if (res.data.code === 20000) {
          const token = res.data.data;
          // 保存token
          localStorage.setItem('token', token);

          // 获取当前登录用户信息
          const resUserInfo = await indexApi.getUserInfo();
          if (resUserInfo.data.code === 20000) {
            this.userInfo = resUserInfo.data.data
            this.$store.commit('setUserInfo', this.userInfo)
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          } else {
            this.$message.error(resUserInfo.data.message || '获取用户信息失败');
          }
          this.visible = false;
          this.$message.success(`登录成功，欢迎回来 ${this.userForm.username}`);
          // 跳转
          this.$router.push('/');
          // 清空表单
          this.userForm = {
            username: '',
            password: ''
          }
        } else {
          this.$message.error(res.data.message || '登录失败');
        }
      } catch (error) {
        this.$message.error('登录失败，请稍后重试');
      }
    },

    // 邮箱登录
    async validateEmailLogin() {
      if (!this.isEmailValid) {
        this.emailError = '请输入有效的邮箱地址';
        return this.$message.error('请输入有效的邮箱地址');
      }
      if (!this.isCodeValid) {
        this.codeError = '请输入6位数字验证码';
        return this.$message.error('请输入6位数字验证码');
      }

      try {
        const res = await loginApi.loginEmailUser(this.form)
        if (res.data.code === 20000) {
          const token = res.data.data;
          // 保存token
          localStorage.setItem('token', token);

          // 获取当前登录用户信息
          const resUserInfo = await indexApi.getUserInfo();

          if (resUserInfo.data.code === 20000) {
            this.userInfo = resUserInfo.data.data
            this.$store.commit('setUserInfo', this.userInfo)
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          } else {
            this.$message.error(resUserInfo.data.message || '获取用户信息失败');
          }

          this.visible = false;
          this.$message.success(`登录成功，欢迎回来 ${this.form.email}`);
          // 跳转
          this.$router.push('/');
          // 清空表单
          this.form = {
            email: '',
            code: '',
          }
        } else {
          this.$message.error(res.data.message || '登录失败');
        }
      } catch (error) {
        this.$message.error('登录失败，请稍后重试');
      }
    },

    // 注册功能(完成)
    async register() {
      if (!this.registerForm.username || !this.registerForm.password || !this.registerForm.email || !this.registerForm.code) {
        return this.$message.error('请填写完整信息');
      }
      if (!this.isRegisterEmailValid) {
        return this.$message.error('请输入有效的邮箱地址');
      }
      if (!this.isRegisterCodeValid) {
        return this.$message.error('请输入6位数字验证码');
      }
      try {
        const res = await registerApi.registerUser(this.registerForm);
        if (res.data.code === 20000) {
          const token = res.data.data;
          // 保存token
          localStorage.setItem('token', token);

          // 获取当前登录用户信息
          const resUserInfo = await indexApi.getUserInfo();
          if (resUserInfo.data.code === 20000) {
            this.userInfo = resUserInfo.data.data
            console.log(`userinfo: ${this.userInfo}`)
            console.log(`userinfores: ${resUserInfo.data.data}`)
            this.$store.commit('setUserInfo', this.userInfo)
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          } else {
            this.$message.error(resUserInfo.data.message || '获取用户信息失败');
          }

          this.visible = false;
          this.$message.success('注册成功，已自动登录');
          // 跳转
          this.$router.push('/');
          // 清空注册表单
          this.registerForm = {
            username: '',
            password: '',
            email: '',
            code: '',
          };
        } else {
          this.$message.error(res.data.message || '注册失败');
        }
      } catch (error) {
        this.$message.error('注册异常，请稍后重试');
      }
    },

    validateEmail() {
      if (this.form.email && !this.isEmailValid) {
        this.emailError = '请输入有效的邮箱地址';
      } else {
        this.emailError = '';
      }
    },

    validateRegisterEmail() {
      if (this.registerForm.email && !this.isRegisterEmailValid) {
        this.registerEmailError = '请输入有效的邮箱地址';
      } else {
        this.registerEmailError = '';
      }
    },

    // 登录时发送验证码
    async sendCode() {
      // 验证邮箱格式
      if (!this.isEmailValid) {
        this.emailError = '请输入有效的邮箱地址';
        return this.$message.error('请输入有效的邮箱地址');
      }

      // 防止重复发送
      if (this.sendingCode || this.timer > 0) {
        return this.$message.warning('请稍后再试');
      }

      this.sendingCode = true; // 开始发送状态

      try {
        // 3. 调用API发送验证码
        const res = await loginApi.sendCode(this.form.email);

        // 4. 处理响应
        if (res.data.code === 20000) {
          this.$message.success('验证码已发送至您的邮箱');

          // 5. 初始化倒计时
          this.timer = 60;
          this.codeError = '';
          this.form.code = ''; // 清空当前验证码输入

          // 6. 清除旧的定时器（如果有）
          if (this.timerInterval) {
            clearInterval(this.timerInterval);
            this.timerInterval = null;
          }

          // 7. 设置新的倒计时定时器
          this.timerInterval = setInterval(() => {
            if (this.timer > 0) {
              this.timer--;
            } else {
              clearInterval(this.timerInterval);
              this.timerInterval = null;
            }
          }, 1000);
        } else {
          // 8. 处理非20000状态码
          this.$message.error(res.data.message || '验证码发送失败');
        }
      } catch (error) {
        // 9. 捕获网络或其他错误
        console.error('发送验证码出错:', error);
        this.$message.error('验证码发送异常，请稍后重试');
      } finally {
        // 10. 无论成功失败都重置发送状态
        this.sendingCode = false;
      }
    },
    // 注册时发送验证码
    async sendRegisterCode() {
      if (!this.isRegisterEmailValid) {
        this.registerEmailError = '请输入有效的邮箱地址';
        return this.$message.error('请输入有效的邮箱地址');
      }

      this.sendingRegisterCode = true;  // 显示发送中状态
      try {
        const res = await registerApi.sendCode(this.registerForm.email);
        if (res.data.code === 20000) {
          this.$message.success('验证码已发送，请查收邮箱');

          // 启动倒计时逻辑
          this.registerTimer = 60;
          if (this.registerTimerInterval) clearInterval(this.registerTimerInterval);

          this.registerTimerInterval = setInterval(() => {
            if (this.registerTimer > 0) {
              this.registerTimer--;
            } else {
              clearInterval(this.registerTimerInterval);
              this.registerTimerInterval = null;
              this.sendingRegisterCode = false;  // 倒计时结束后恢复可发送状态
            }
          }, 1000);

        } else {
          this.$message.error(res.data.message || '验证码发送失败');
        }
      } catch (error) {
        this.$message.error('验证码发送异常，请稍后重试');
      } finally {
        this.sendingRegisterCode = false;  // 确保无论成功失败都恢复状态
      }
    },

    quickRegister() {
      if (this.infor === '已有账号，快速登录') {
        this.activeTab = "account"
        this.infor = '快速注册'
      } else {
        this.activeTab = 'register';
        this.infor = '已有账号，快速登录'
      }
    },

    validateCode() {
      if (this.form.code && !this.isCodeValid) {
        this.codeError = '请输入6位数字验证码';
      } else {
        this.codeError = '';
      }
    },
  },

  beforeDestroy() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
    if (this.registerTimerInterval) {
      clearInterval(this.registerTimerInterval);
    }
  },
};
</script>

<style scoped>
/* dialog 居中，圆角等 */
.login-dialog >>> .el-dialog__wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-dialog >>> .el-dialog {
  border-radius: 20px;
}

.login-dialog >>> .el-dialog__headerbtn {
  top: 16px;
  right: 16px;
  width: 24px;
  height: 24px;
  font-size: 20px;
}

.login-dialog >>> .el-dialog__close {
  font-size: 22px;
  color: #909399;
}

.login-dialog >>> .el-dialog__close:hover {
  color: #409eff;
}

.login-container {
  background: white;
  border-radius: 16px;
  padding: 28px 35px 35px;
  box-sizing: border-box;
  width: 100%;
  user-select: none;
}

.login-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 28px;
  user-select: none;
}

.tab {
  font-size: 16px;
  margin: 0 16px;
  cursor: pointer;
  position: relative;
  padding-bottom: 8px;
  color: #666;
  transition: color 0.3s;
}

.tab.active,
.tab:hover {
  color: #409eff;
  font-weight: 600;
}

.tab.active::after,
.tab:hover::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: #409eff;
  border-radius: 3px;
}

/* 输入框整体增加高度，字体更清晰 */
.login-input {
  margin-bottom: 25px;
  width: 100%;
}

.el-input__inner {
  height: 50px !important;
  line-height: 50px !important;
  font-size: 16px;
  border-radius: 8px !important;
  transition: border-color 0.3s;
  box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.05);
}

.el-input__inner:hover {
  border-color: #a0bfff !important;
}

/* 错误提示样式 */
.error-hint {
  color: #f56c6c;
  font-size: 12px;
  margin-bottom: 10px;
  height: 16px;
}

/* 密码框眼睛样式 */
.password-input >>> .el-input__icon {
  color: #409eff !important;
  font-weight: 600;
  font-size: 22px !important;
  cursor: pointer;
}

.password-input >>> .password-hidden::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 1px;
  height: 16px;
  background: #409eff;
  transform: translate(-50%, -50%) rotate(45deg);
  transform-origin: center;
}

/* 底部行 */
.form-bottom-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 35px;
}

.auto-login {
  font-size: 14px;
}

.forgot-password {
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #66b1ff, #409eff);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s;
}

.login-btn:hover {
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
  transform: translateY(-2px);
}

.login-btn:disabled {
  background: #a0cfff !important;
  cursor: not-allowed !important;
  opacity: 0.7;
}

/* 验证码输入框容器 */
.code-input-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

/* 验证码输入框 */
.code-input {
  flex: 1;
}

.code-input >>> .el-input__inner {
  border-radius: 8px 0 0 8px !important;
}

/* 验证码按钮 */
.code-btn {
  border-radius: 0 8px 8px 0 !important;
  height: 40px !important;
  font-size: 12px !important;
  padding: 0 16px !important;
  color: #409eff !important;
  background: #fff !important;
  border: 1px solid #409eff !important;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  margin-left: -1px; /* 消除边框重叠 */
}

.code-btn:not([disabled]):hover {
  background: #f0f7ff !important;
}

.code-btn[disabled] {
  background: #f5f5f5 !important;
  border-color: #e0e0e0 !important;
  color: #a0a0a0 !important;
  cursor: not-allowed !important;
}

.countdown-btn {
  color: #a0a0a0 !important;
  border-color: #e0e0e0 !important;
}

/* 快速注册 */
.quick-register {
  text-align: center;
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
  margin-bottom: 16px;
  user-select: none;
}

/* 第三方登录图标 */
.third-login {
  display: flex;
  justify-content: center;
  gap: 24px;
  font-size: 24px;
  user-select: none;
}

.icon {
  width: 40px;
  height: 40px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f5f5f5;
  transition: all 0.3s;
  cursor: pointer;
  user-select: none;
}

.icon:hover {
  transform: translateY(-3px);
}

.icon.wechat::before {
  content: "\1F4F1";
  color: #06c;
}

.icon.qq::before {
  content: "\1F47B";
  color: #409eff;
}

.icon.weibo::before {
  content: "\1F4F0";
  color: #f40;
}
</style>
